<template>
	<Mask />
  <div class="a4-body" id="clip">
    <Header :detailed="state.detailed" :category-item="categoryItem" />
    <div class="render-content">
      <AnswerComponent v-if="state.AnswerComponent" class="print-component" :print="true" :category-item="categoryItem" :size="categoryItem.printSize" :get-result="getResult" :user-id="state.detailed.user_id" :topic-data="state.detailed" :show-input="false" :category-id="state.categoryId" />
    </div>
    <Footer :qr-code="state.qr_code" />
  </div>
</template>
<script setup>
import { ref, reactive, computed, onMounted, nextTick } from "vue"
import { useRoute } from "vue-router"
import { useStore } from "vuex"

import defaultImag from "@/assets/default-logo.png"
import wx from 'weixin-js-sdk'
import MathFormula from  "@/components/mathFormula/index.vue"
import Code from  "@/components/code/index.vue"
import Header from  "./header.vue"
import Footer from  "./footer.vue"
import Mask from  "@/components/loadingMask/index.vue"
import { useTopicCreate } from "@/hooks"
import { getStaticUrl, usePingYi } from "@/utils"
import { saveShare } from "@/utils/exportImage"
import { getPrintDetailed, getListDataByIds, delPrint, getUserInfo, getUserInfoCode } from "@/api"
import { useDict } from "@/dict"
const store = useStore()
const { useDictList, useDictItem } = useDict()
const { polyphonicPingYiWords } = usePingYi()
const { useFormatCreateData, useTopicCreateList } = useTopicCreate()
window.wx = wx
const categoryOption = useDict('categoryOption')
const grade = useDict('gradeOptions')
const route = useRoute()
sessionStorage.setItem('token', route.query.token)
import AnswerComponent from "@/components/topicComponents/index.vue"
// 导出页面为PDF格式
import html2Canvas from 'html2canvas';

const state = reactive({
	query: {
		id: route.query.id,
		name: route.query.name,
		icon: route.query?.icon || 1,
		delete: route.query.delete
	},
	userinfo: {},
	detailed: {},
	detailedAnser: {},
	text: '',
	qr_code: "",
	user_qr_code: "",
	openShare: false,
	shareUrl: '',
	allWords: [],
	wordsList: [],
	lessonName: "",
	poetry: false,
	AnswerComponent: false,
	shareIcon: '',
	categoryId: ''
})

const categoryItem = ref({})

const getDetailed = async () => {
	const userinfo = await getUserInfo()
	// 伙伴
	if(userinfo.content.distribution) {
		state.user_qr_code = userinfo.content.qr_code_image
	}else{
		const otherUserinfo = await getUserInfoCode({id: userinfo.content.parent_id})
		state.user_qr_code = otherUserinfo.content.qr_code_image
	}
	getPrintDetailed({id: state.query.id}).then(async (res) => {
		const data = res.content
		state.categoryId = data.category_id
		// 数学
		if(state.categoryId === 9) {
			categoryItem.value = useDictItem(data.sub_category_id * 1, 'mathKindergarten')
			state.detailed = data
			state.AnswerComponent = true
			await nextTick()
			getResult()
		}
		// 语文
		if(state.categoryId === 8) {
			categoryItem.value = useDictItem(data.sub_category_id * 1, 'categoryOption')
			getListDataByIds({ids: data.content.split(',')}).then(async (res) => {
				const formatData = await useTopicCreateList({
					isRand: true,
					list: res.content,
					type: categoryItem.value.topicComponent,
					data_source_id: categoryItem.value.data_source_id,
					category_id: categoryItem.value.value,
				})
				data.content = JSON.stringify(formatData)
				state.detailed = data
				state.AnswerComponent = true
			})
		}
		// 删除题目
		state.query.delete && delPrint({id:data.id})
	})
}

const getResult = () => {
	nextTick(() => {
		setTimeout(() => {
			createImg()
		}, 2000)
	})
}


const createImg = async () => {
	await nextTick()
	await getBaseimgFile(getStaticUrl(state.user_qr_code))
	await nextTick()
	setTimeout(() => {
		// 大图
		saveShare({ domId: "clip" }).then((bigImg) => {
			// 小图
			saveShare({ domId: "clip", scale: 0.5 }).then((smallImg) => {
				wx.miniProgram.postMessage({
					data: {
						url: bigImg,
						smallImg
					}
				})
				wx.miniProgram.navigateBack()
			})
		})
		.catch(() => {
			wx.miniProgram.navigateBack()
		})
	}, 500)
}

const getBaseimgFile = (url) => {
	return new Promise((resolve,reject)=>{ 
		//图片路径转换为Base64↓
		let image = new Image(); // 一定要设置为let，不然图片不显示
		image.setAttribute('crossOrigin', '*'); // 解决跨域问题
		image.src = (url || defaultImag) + '?time=' + new Date().valueOf();//网络图片路径
		image.onload = () => {
			var canvas = document.createElement("canvas");
			canvas.width = image.width;
			canvas.height = image.height;
			var context = canvas.getContext("2d");
			context.drawImage(image, 0, 0, image.width, image.height);
			var quality = 0.8;
			var dataURL = canvas.toDataURL("image/jpeg", quality); 
			// 使用toDataUrl将图片转换成jpeg的格式,不要把图片压缩成png，因为压缩成png后base64的字符串可能比不转换前的长！
			state.qr_code = dataURL
			resolve(); //成功
		};
		
		image.onerror = () => {
			alert('失败')
			wx.miniProgram.navigateBack()
			reject()
		}
	})
}


const dataURLtoBlob = (dataurl) => {
	var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
	while(n--){
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new Blob([u8arr], {type:mime});
}
onMounted(() => {
	getDetailed()
})




const htmlToPdf = async (dom, title) => {
    var pdfTitle = title;  //pdf的名称
    var pdfDom = document.querySelector(dom);
    html2Canvas(pdfDom, {
        allowTaint:false,
        useCORS: true,
        scale: 3
    }).then(function (canvas) {
        console.log(canvas);
        let pageData = canvas.toDataURL('image/jpeg', 3.0);
        const link = document.createElement("a");
        link.href = pageData;
        link.download = `图片.png`;
        link.click();
    });

};
// setTimeout(() => {
//   htmlToPdf('#clip', '本年度数据统计分析报告');
// })



</script>
<style scoped>
.a4-body {
  width: 794px; /* 210mm * 300 / 25.4 */
  height: 1123px; /* 297mm * 300 / 25.4 */
  position: relative; /* 对于绝对定位的内容 */
  background-color: #fff;
}
.render-content {
	padding: 40px 20px;
	height: 865px;
	box-sizing: border-box;
}
</style>